package org.jeecg.modules.third.openapi;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.LngLonUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.ecloud.sdk.util.DateUtil;
import org.jeecg.modules.third.openapi.dto.ParkInfo;
import org.jeecg.modules.third.openapi.dto.WaybillRoute;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.shipping.entity.PointDataListVO;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 中物联轨迹
 */

@Service
@Slf4j
public class ZWLWaybillRouteService {


    @Value(value = "${zwl.baseUrl:}")
    private String baseUrl;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IHyVehicleService vehicleService;

    @Autowired
    private ZWLOpenApiService zwlOpenApiService;

    private final String ZWL_API_TOKEN_KEY = "ZWL_Api_Token";


    //查看实时轨迹(未完成)

    public Result<?> vLastLocationVinCom(HyVehicle vehicle) {



           /* String res = cn.hutool.http.HttpUtil.post(url, JSONUtil.toJsonStr(reqBody));
            log.info("中物联返回参数回执 <- {}" + res);
            JSONObject jsonObject = JSONObject.parseObject(res);
            int status = jsonObject.getIntValue("status");
            //把返回的状态码与字典值中的状态进行比对，如果一直则返回字段值的内容
            List<DictModel> zwl_status = sysDictMapper.queryDictItemsByCode("ZWL_status");

            if (status != 1001) {

                for (DictModel model : zwl_status) {
                    if (String.valueOf(status).equals(model.getValue())) {
                        return Result.error(model.getText());
                    }
                }

            }*/
        return Result.OK();
    }


    //获取中物联历史轨迹
    public WaybillRouteVO getHistoryShippingTrack(String vehicleNo, String startTime, String endTime, String toType) {
        log.info("获取中物联历史轨迹,参数{} {} {}", vehicleNo, startTime, endTime);
        HyVehicle hyVehicle = vehicleService.getHyVehicleByVehicleNumber(vehicleNo);
        if (hyVehicle==null){
            throw new JeecgBootException("车辆没有记录");
        }
        String vco = hyVehicle != null && StringUtils.isNotEmpty(hyVehicle.getVehiclePlateColorCode()) ? hyVehicle.getVehiclePlateColorCode() : "2";
        //中交轨迹和交通部字典值不一样，黄绿车牌交通部要求93，中交是3
        if ("93".equals(vco)) {
            vco = "3";
        }


        long days = DateUtil.getDaySub(startTime, endTime);

        List<WaybillRoute> waybillRoutes = new ArrayList<>();
        List<ParkInfo> parkInfos = new ArrayList<>();
        WaybillRouteVO waybillRouteVO = new WaybillRouteVO();


        HyConfig systemConfig = HyConfigUtils.getConfig();
        String token = (String) redisUtil.get(ZWL_API_TOKEN_KEY);
        if (token == null) {
            token = zwlOpenApiService.getLoginToken();
        }
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("token", token);
        reqMap.put("cid", systemConfig.getZwlCid());
        reqMap.put("srt", systemConfig.getZwlSrt());
        reqMap.put("vin", hyVehicle.getVin());
        reqMap.put("vclN", hyVehicle.getVehicleNumber() + "_" + vco);
        reqMap.put("qryBtm", startTime);
        reqMap.put("qryEtm", endTime);
        log.info("中物联的请求参数->{}" + reqMap);
        try {
            if (days <= 1) {
                String res = zwlOpenApiService.queryZwlTruckHisTrack(reqMap);
                log.info("中物联返回参数回执 <- {}" + res);
                JSONObject jsonObject = JSONObject.parseObject(res);
                if (StringUtils.isNotEmpty(res)) {
                    String result = jsonObject.getString("result");
                    waybillRoutes = JSONObject.parseArray(result, WaybillRoute.class);
                }

            } else {
                for (int i = 0; i < days; i++) {
                    reqMap.put("token", token);
                    reqMap.put("cid", systemConfig.getZwlCid());
                    reqMap.put("srt", systemConfig.getZwlSrt());
                    reqMap.put("vin", hyVehicle.getVin());
                    reqMap.put("vclN", hyVehicle.getVehicleNumber() + "_" + vco);

                    //转换成毫秒数

                    Date statusDtLoading = DateUtils.stringToDateTime(startTime);
                    Date statusDtUnloading = DateUtils.stringToDateTime(endTime);
                    long startMillis = DateUtils.getMillis(statusDtLoading);
                    long endMillis = DateUtils.getMillis(statusDtLoading) + 86400000;


                    Date date = new Date(startMillis);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String newStartTime = sdf.format(date);
                    String newEndTime;
                    if (i == days - 1) {
                        long endMillis1 = DateUtils.getMillis(statusDtUnloading);
                        Date date2 = new Date(endMillis1);
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        newEndTime = sdf2.format(date2);
                    } else {
                        Date date2 = new Date(endMillis);
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        newEndTime = sdf2.format(date2);
                        startTime = newEndTime;
                    }

                    reqMap.put("qryBtm", newStartTime);
                    reqMap.put("qryEtm", newEndTime);
                    String res = zwlOpenApiService.queryZwlTruckHisTrack(reqMap);
                    log.info("中物联返回参数回执 <- {}" + res);
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    if (StringUtils.isNotEmpty(res)) {
                        String result = jsonObject.getString("result");
                        waybillRoutes.addAll(JSONObject.parseArray(result, WaybillRoute.class));
                    }
                }
            }
        } catch (Exception e) {
            log.info("ZWLWaybillRouteService  getHistoryShippingTrack  Exception |{}", e.getMessage());
            throw new JeecgBootException(e.getMessage());
        }
        Map<String, ParkInfo> parkInfoMaps = new HashMap<>();
        if (CollectionUtils.isNotEmpty(parkInfos)) {
            for (ParkInfo parkInfo : parkInfos) {
                parkInfoMaps.put(parkInfo.getParkLon() + "_" + parkInfo.getParkLat(), parkInfo);
            }
        }
        if (CollectionUtils.isNotEmpty(waybillRoutes)) {

            List<PointDataListVO> pointDataListVOs = new ArrayList();
            List<List<String>> valueList = new ArrayList<>();
            List<ParkInfo> parkInfoList = new ArrayList<>();
            for (WaybillRoute waybillRoute : waybillRoutes) {

                PointDataListVO pointDataListVO = new PointDataListVO();
                //Double.parseDouble(waybillRoute.getSpd())
                Double spd = Double.valueOf(waybillRoute.getSpd());
                pointDataListVO.setCs(spd);

                double lat = Double.valueOf(waybillRoute.getLat()) / 600000;
                double lan = Double.valueOf(waybillRoute.getLon()) / 600000;
                double[] gcj02 = LngLonUtil.gps84_To_Gcj02(lat, lan);

                pointDataListVO.setLat(String.valueOf(gcj02[0]));
                pointDataListVO.setLng(String.valueOf(gcj02[1]));

                String gtm = waybillRoute.getGtm().replace("/", "");
                String strGtm = DateUtils.strDateTimeToFormatString(gtm);
                pointDataListVO.setReceiveTime(strGtm);
                //停车信息
                if (parkInfoMaps.size() > 0) {
                    String key = waybillRoute.getLon() + "_" + waybillRoute.getLat();
                    if (parkInfoMaps.get(key) != null) {

                        for (ParkInfo parkInfo : parkInfos) {

                            String key1 = parkInfo.getParkLon() + "_" + parkInfo.getParkLat();
                            if (key1.equals(key)) {
                                String parkBte = StringUtils.isNotBlank(parkInfo.getParkBte()) ? DateUtils.timestamptoStr2(Long.valueOf(parkInfo.getParkBte())) : "";
                                String parkEte = StringUtils.isNotBlank(parkInfo.getParkEte()) ? DateUtils.timestamptoStr2(Long.valueOf(parkInfo.getParkEte())) : "";

                                parkInfo.setParkBte(parkBte);
                                parkInfo.setParkEte(parkEte);
                                parkInfo.setParkLon(String.valueOf(gcj02[1]));
                                parkInfo.setParkLat(String.valueOf(gcj02[0]));
                                parkInfoList.add(parkInfo);

                                pointDataListVO.setParkAdr(parkInfo.getParkAdr());
                                pointDataListVO.setParkBte(parkBte);
                                pointDataListVO.setParkEte(parkEte);
                                pointDataListVO.setParkLon(String.valueOf(gcj02[1]));
                                pointDataListVO.setParkLat(String.valueOf(gcj02[0]));
                                pointDataListVO.setParkMins(parkInfo.getParkMins());
                            }
                        }
                    }
                }

                pointDataListVOs.add(pointDataListVO);

                List<String> valueListString = new ArrayList<>();
                valueListString.add(String.valueOf(gcj02[1]));
                valueListString.add(String.valueOf(gcj02[0]));
                valueList.add(valueListString);
            }

            waybillRouteVO.setParkInfoList(parkInfoList);
            waybillRouteVO.setLineArray(valueList);
            waybillRouteVO.setPointDataList(pointDataListVOs);
        }
        return waybillRouteVO;

    }

    /**
     * 车辆入网验证(车牌号_颜色，例如：京 xxx_2)
     *
     * @param
     * @return
     */
    public Result<?> checkVehicleStatus(HyVehicle hyVehicle) {

        try {

            HyConfig systemConfig = HyConfigUtils.getConfig();
            String token = (String) redisUtil.get(ZWL_API_TOKEN_KEY);
            if (token == null) {
                token = zwlOpenApiService.getLoginToken();
            }
            HyVehicle vehicle = vehicleService.getHyVehicleByVehicleNumber(hyVehicle.getVehicleNumber());
            String vco = vehicle != null && StringUtils.isNotEmpty(vehicle.getVehiclePlateColorCode()) ? vehicle.getVehiclePlateColorCode() : "2";
            //中交轨迹和交通部字典值不一样，黄绿车牌交通部要求93，中交是3
            if ("93".equals(vco)) {
                vco = "3";
            }
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("token", token);
            reqMap.put("cid", systemConfig.getZwlCid());
            reqMap.put("srt", systemConfig.getZwlSrt());
            reqMap.put("vin", vehicle.getVin());
            reqMap.put("vclN", vehicle.getVehicleNumber() + "_" + vco);

            log.info("中物联车辆入网确认的请求参数->{}" + reqMap);
            String url = baseUrl + "/api/GetData/checkVehicleExistV2";

            log.info("获取中物联入网V2请求参数 -> {} {}", url, JSONUtil.toJsonStr(reqMap));
            String res = zwlOpenApiService.checkVehicleExist(reqMap);
            log.info("获取中物联联入网V2回执 <- {}", res);

            JSONObject jsonObject = JSONObject.parseObject(res);

            String result = jsonObject.getString("result");
            if (result.equals("no")){
                    return Result.error("验证失败,车辆未入网。");
            }else {
                String timeStamp = jsonObject.getString("result");
                Date millisecondDate= new Date(Long.valueOf(timeStamp));
                return Result.OK(DateUtils.dateTimeToString(millisecondDate));
            }


        } catch (Exception e) {
            e.printStackTrace();
            log.info("中交慧联入网验证异常 ,{}", e.getMessage());
            throw new JeecgBootException(e.getMessage());
        }
    }


}
